#!/usr/bin/python

"""List files in a specified date range"""

import os, sys, time, optparse

p = optparse.OptionParser(usage="usage: %prog -s 10/22/2010_10:00:00 -e 10/08/2011_09:00:00 -p /home/myuser/logs")
p.add_option('--start_time', '-s', help="start time format: mm/dd/YYYY_HH:MM:SS", action="store")
p.add_option('--end_time', '-e', help="end time format: mm/dd/YYYY_HH:MM:SS", action="store")
p.add_option('--display', '-d', help="display start/end time before printing file names", action="store_true")
p.add_option('--no_dir', '-n', help="only display regular files, no directories", action="store_true")
p.add_option('--path', '-p', help="full path to search: /home/user", action="store")
p.add_option('--timestamp', '-t', help="print timestamp along with filenames & sorts output by timestamp", action="store_true")
(opts, args)=p.parse_args()

def time_conv(timestr):
    return time.mktime(time.strptime(timestr, '%m/%d/%Y_%H:%M:%S'))

def time_asconv(timestr):
    return time.asctime(time.strptime(timestr, '%m/%d/%Y_%H:%M:%S'))


if not opts.start_time:
	opts.start_time=raw_input("\nEnter your start time in format: mm/dd/YYYY_HH:MM:SS\n")
if not opts.end_time:
	opts.end_time=raw_input("\nEnter your end time in format: mm/dd/YYYY_HH:MM:SS\n")
if not opts.path:
	opts.path=raw_input("\nEnter the full path to the directory you'd like to check.\n")

starttime=time_conv(opts.start_time)
endtime=time_conv(opts.end_time)
if endtime < starttime:
    print "\nERROR:  Your start_time must be before your end_time!\n"
    sys.exit(1)

if opts.display:
    print "Start Time:\t", time_asconv(opts.start_time)
    print "End Time:\t", time_asconv(opts.end_time), "\n"

mypath=os.path.abspath(opts.path)
timedict={}

try:  
    os.chdir(os.path.abspath(mypath))
    for file in sorted(os.listdir(mypath)):
        mtime=os.stat(os.path.join(mypath, file)).st_mtime
        if starttime <= mtime <= endtime:
	    if opts.no_dir:
	        if os.path.isfile(file):
	            fname=file
		else:
		    continue 
	    else:
	        fname=file
            if opts.timestamp:
                #fname=time.ctime(mtime) + '\t' + fname 
                timedict[fname]=mtime
            else:
                print fname 
    #print timedict
    if opts.timestamp:
        for key, value in sorted(timedict.iteritems(), key=lambda (k,v): (v,k)):
            print "%s:\t%s" % (time.ctime(timedict[key]), key)
except OSError, error:
    print "ERROR: ", error
    sys.exit(1)

